package com.camel.base.exceptions;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import com.camel.core.config.ExceptionCHConfig;
import com.camel.core.entity.Result;
import com.camel.core.utils.ResultUtil;
import com.netflix.client.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author camel
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Autowired
    private ExceptionCHConfig chConfig;

    /**
     * 全局异常拦截
     * @param e
     * @param req
     * @param resp
     * @throws IOException
     */
    @ExceptionHandler
    public Result handlerException(RuntimeException e, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println(chConfig.getMessages());
        e.printStackTrace();
        return ResultUtil.error(500, e.getMessage());
    }


    @ExceptionHandler({NotRoleException.class})
    public Result handlerNoRoleException(RuntimeException e, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        return ResultUtil.error(500, "对不起,您没有访问权限!");
    }

    @ExceptionHandler({ClientException.class})
    public Result handlerClientException(ClientException e, HttpServletRequest req, HttpServletResponse resp) {
        return ResultUtil.error(500, e.getErrorMessage());
    }
}
